<template>
  <Layout style="height: 100%;" class="main">
    <Sider
      hide-trigger
      collapsible
      :width="256"
      :collapsed-width="64"
      v-model="collapsed"
      class="left-sider"
      :style="{overflow: 'hidden'}"
    >
      <side-menu
        accordion
        ref="sideMenu"
        :active-name="$route.name"
        :collapsed="collapsed"
        @on-select="turnToPage"
        :menu-list="menuList"
      >
        <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
        <div class="logo-con">
          <div v-show="!collapsed" class="logo_ttile" v-text="main_title"></div>
          <!-- <img v-show="!collapsed" :src="main_title_img" class="max-logo" key="max-logo" /> -->
          <img
            v-show="collapsed"
            :src="'/vendors/images/' + main_logo"
            class="min-logo"
            key="min-logo"
          />
        </div>
      </side-menu>
    </Sider>
    <Layout style="overflow: hidden;" id="main">
      <Header class="header-con">
        <header-bar :collapsed="collapsed" @on-coll-change="handleCollapsedChange">
          <user :user-avator="userAvator" :user-name="userName" />
          <fullscreen v-model="isFullscreen" style="margin-right: 16px;" />
        </header-bar>
      </Header>
      <Content class="main-content-con">
        <Layout class="main-layout-con">
          <div class="tag-nav-wrapper">
            <tags-nav
              :value="$route"
              @input="handleClick"
              :list="tagNavList"
              @on-close="handleCloseTag"
            />
          </div>
          <Content class="content-wrapper">
            <keep-alive :include="cacheList">
              <router-view />
            </keep-alive>
          </Content>
        </Layout>
      </Content>
      <Content class="main-bottom-con">
        <div class="main-bottom-con">
          <div class="main-bottom">
            <a
              href="http://www.jnaw.top"
              target="_blank"
              class="html-button"
            >©2020 AllView CWBU All Rights Reserved. v{{ version }}</a>
          </div>
        </div>
      </Content>
    </Layout>
  </Layout>
</template>
<script>
import SideMenu from "./components/side-menu";
import HeaderBar from "./components/header-bar";
import TagsNav from "./components/tags-nav";
import User from "./components/user";
import Fullscreen from "./components/fullscreen";
import Language from "./components/language";
import { mapMutations, mapActions } from "vuex";
import { getNewTagList, getNextRoute, routeEqual } from "@/libs/util";
import minLogo from "@/assets/images/logo-min.jpg";
import maxLogo from "@/assets/images/logo.jpg";
import "./main.less";
import Cookies from "js-cookie";
import util from "../../libs/util";
import Util from "../../libs/util";
import Utils from "../../libs/mod.utils";
import dbUtils from "../../libs/mod.local.db";
import IndexDB from "../../libs/mod.indexDB";
import baiduMap from "../../libs/mod.baiduMap";
import os from "../../libs/mod.os";

import im from "../../mod/im";
import Consts from "../../assets/consts";

import Log from "../../mod/log";
let log = new Log("main");

export default {
  name: "Main",
  components: {
    SideMenu,
    HeaderBar,
    Language,
    TagsNav,
    Fullscreen,
    User
  },
  data() {
    return {
      collapsed: false, // 左侧菜单栏是否收起
      minLogo,
      maxLogo,
      isFullscreen: false,
      version: util.version,
      uid: "",
      username: "",
      menuList: [],
      main_title: Util.main_title,
      main_logo: Util.main_logo,
      main_title_img: "/vendors/images/" + Util.main_title_img,
      longitude: 0, // 定位信息
      latitude: 0,
      address: ""
    };
  },
  computed: {
    localMessage_unread() {
      return this.$store.state.app.localMessage_unread;
    },
    tagNavList() {
      return this.$store.state.app.tagNavList;
    },
    tagRouter() {
      return this.$store.state.app.tagRouter;
    },
    userAvator() {
      return this.$store.state.app.userAvator;
    },
    userName() {
      return this.$store.state.app.userName;
    },
    cacheList() {
      return this.tagNavList.length
        ? this.tagNavList
            .filter(item => !(item.meta && item.meta.notCache))
            .map(item => item.name)
        : [];
    },
    /*menuList () {
       return this.$store.getters.menuList
       },*/
    local() {
      return this.$store.state.app.local;
    }
  },
  watch: {
    $route(newRoute) {
      this.setBreadCrumb(newRoute.matched);
      this.setTagNavList(getNewTagList(this.tagNavList, newRoute));
    }
  },
  created() {
    var _this = this;
    _this.login();
    _this.getMenuList();
    var title = Util.title(); // 页面标题
    var page_icon = Util.page_icon; // 页面ico
    window.document.title = title;
    // 设置ico
    var linkEle = document.getElementById("link_icon_id");
    linkEle.href = "/vendors/images/" + page_icon;
    linkEle.type = "";
    linkEle.type = "image/x-icon";
  },
  mounted() {
    var _this = this;
    /**
     * @description 初始化设置面包屑导航和标签导航
     */
    this.setTagNavList();
    this.addTag({
      route: this.$store.state.app.homeRoute
    });
    this.setBreadCrumb(this.$route.matched);
    // 设置初始语言
    this.setLocal(this.$i18n.locale);

    _this.$nextTick(function() {});
  },
  methods: {
    ...mapMutations(["setBreadCrumb", "setTagNavList", "addTag", "setLocal"]),
    ...mapActions(["handleLogin"]),
    // 菜单
    getMenuList: function() {
      var _this = this;
      var menuList = this.$store.getters.menuList;
      var returnMenuList = [];
      var routerNameMenuList = [];
      var volunteerMenuListName = Util.constant.volunteerMenuListName;
      var loginDataStr = localStorage.getItem("loginData") || "";
      var type = "";
      if (loginDataStr != "") {
      } else {
        routerNameMenuList = volunteerMenuListName;
      }
      // routerNameMenuList = Utils.onlyArray(routerNameMenuList);
      // if (routerNameMenuList.length > 0 && returnMenuList.length == 0) {
      //   returnMenuList = _this.getShowMenuList(menuList, routerNameMenuList);
      // }
      returnMenuList = menuList; // 全部菜单
      _this.menuList = returnMenuList;
    },
    // 根据权限获取菜单
    getShowMenuList: function(menuList, routerNameMenuList) {
      var _this = this;
      for (var k in menuList) {
        if (!menuList[k]) {
          continue;
        }
        var name = menuList[k].name;
        var children = menuList[k].children;
        if (routerNameMenuList.indexOf(name) > -1) {
          if (children && children.length > 0) {
            for (var i in menuList[k].children) {
              if (!menuList[k].children[i]) {
                continue;
              }
              var name2 = menuList[k].children[i].name;
              var children2 = menuList[k].children[i].children;
              if (routerNameMenuList.indexOf(name2) > -1) {
                if (children2 && children2.length > 0) {
                  for (var l in menuList[k].children) {
                    if (!menuList[k].children[i].children[l]) {
                      continue;
                    }
                    var name3 = menuList[k].children[i].children[l].name;
                    if (routerNameMenuList.indexOf(name3) > -1) {
                    } else {
                      menuList[k].children[i].children[l] = {};
                    }
                  }
                }
              } else {
                menuList[k].children[i] = {};
              }
            }
          }
        } else {
          menuList[k] = {};
        }
      }
      return menuList;
    },
    turnToPage(route) {
      let { name, params, query } = {};
      if (typeof route === "string") name = route;
      else {
        name = route.name;
        params = route.params;
        query = route.query;
      }
      if (name.indexOf("isTurnByHref_") > -1) {
        window.open(name.split("_")[1]);
        return;
      }
      this.$router.push({
        name,
        params,
        query
      });
    },
    handleCollapsedChange(state) {
      this.collapsed = state;
    },
    handleCloseTag(res, type, route) {
      let openName = "";
      if (type === "all") {
        this.turnToPage("home");
        openName = "home";
      } else if (routeEqual(this.$route, route)) {
        if (type === "others") {
          openName = route.name;
        } else {
          const nextRoute = getNextRoute(this.tagNavList, route);
          this.$router.push(nextRoute);
          openName = nextRoute.name;
        }
      }
      this.setTagNavList(res);
      this.$refs.sideMenu.updateOpenName(openName);
    },
    handleClick(item) {
      this.turnToPage(item);
    },
    login: function() {
      var _this = this;
      var login_mobile = Utils.getCookie("login_mobile");
      var login_password = Utils.getCookie("login_password");
      var mobile = "";
      var password = "";
      if (login_mobile && login_password) {
        login_password = Utils.uncompile(login_password); //解密
        mobile = login_mobile;
        password = login_password;
      }
      var data = {
        mobile: mobile,
        password: password
      };
      var params = {
        url: "/user/login",
        type: Util.method.post,
        data: data,
        success: _successFun
      };
      Util.ajax(_this, params);
      function _successFun(res) {
        if (res.result == 0) {
          var data = res.data;
          localStorage.setItem("loginData", Util.toStr(data));
          localStorage.setItem("userInfo", Util.toStr(data));
          _this.id = data.id;
          _this.username = data.name;
          _this.mobile = data.mobile;

          var login_password = Utils.compile(password); //加密
          Utils.delCookie("login_mobile");
          Utils.delCookie("login_password");
          Utils.setCookie("login_mobile", mobile, 30);
          Utils.setCookie("login_password", login_password, 30);

          _this.goto(data);
        } else {
          _this.$Message.destroy();
          _this.$Message.error("登录超时，请重新登录!");
          // 退出登录
          _this.loginOut();
          _this.$store.commit("logout", _this);
          _this.$store.commit("clearOpenedSubmenu");
          sessionStorage.setItem("logout", 1);
          _this.$router.push({
            name: "login"
          });
        }
      }
    },
    goto: function(_data) {
      var _this = this;
      var username = _data.name;
      var mobile = _data.mobile;

      var thumb = _data.thumb ? _data.thumb : Util.constant.personImg;
      Cookies.set("token", _data.id);
      _this.$store.state.app.userAvator = thumb;
      _this.$store.state.app.userName = username;
    },
    loginOut: function() {
      var _this = this;
      setTimeout(function() {
        var data = {};
        var params = {
          url: "/user/logout",
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            console.log("退出成功");
          } else {
          }
        }
      }, 1000);
    },
    getUserInfoFun: function() {
      var _this = this;
      var data = {
        id: _this.uid,
        username: _this.username
      };
      var params = {
        url: "/user/query",
        type: Util.method.post,
        data: data,
        success: _successFun
      };
      Util.ajax(_this, params);
      function _successFun(res) {
        if (res.result == 0) {
          var _data = res.data || {};
          localStorage.setItem("userInfo", Util.toStr(_data));
          var userName = _data.name;
          var username = _data.username;
          var mobile = _data.mobile;
          var avatar = _data.avatar;
          var thumb = avatar.thumb ? avatar.thumb : Util.constant.personImg;
          Cookies.set("token", _data.id);
          _this.$store.state.app.userAvator = thumb;
          _this.$store.state.app.userName = userName;
        } else {
          _this.$Message.destroy();
          _this.$Message.error("查询用户信息失败!");
        }
      }
    },
    // 消息
    toMessagePage: function() {
      this.$router.push({
        name: "localMessage_index"
      });
    },
    // 收藏
    toCollectionPage: function() {
      this.$router.push({
        name: "collection"
      });
    }
  }
};
</script>
